import React, {useEffect, useState} from "react";
import {Form, Button, Input, Tabs, message, Modal, notification} from "antd";
import styles from './index.module.scss';
import logo from '@/assets/images/logo-spug-txt.png';
import {UserOutlined, LockOutlined, CopyrightOutlined, GithubOutlined, MailOutlined} from '@ant-design/icons';
import http from "@/common/http";
import {LOGIN_INFO} from "@/common/constant";
import {useNavigate} from "react-router-dom";

function Login() {

  const navigate = useNavigate();
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [loginType, setLoginType] = useState('default');
  const [counter, setCounter] = useState(0);
  const [codeLoading, setCodeLoading] = useState(false);

  useEffect(() => {
    setTimeout(() => {
      if (counter > 0) {
        setCounter(counter - 1)
      }
    }, 1000)
  }, [counter])

  function handleSubmit() {
    const formData = form.getFieldsValue();
    if (!formData.captcha) {
      return message.error('请输入验证码');
    }
    if (!formData.username) {
      return message.error('请输入用户名');
    }
    if (!formData.password) {
      return message.error('请输入密码');
    }

    setLoading(true);

    http({
      method: 'POST',
      url: '/api/auth/oauth/token',
      headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'},
      data: `grant_type=password&scope=all&type=${loginType}&username=${formData.username}&password=${formData.password}`,
      auth: {username: 'clientapp', password: 'abcd'}
    }).then((res: any) => {
      console.log(res)
      if (res.code === 0) {
        localStorage.setItem(LOGIN_INFO, res.data)
        navigate("/", {replace: true});
      }
    }).finally(() => setLoading(false))
  }

  function handleCaptcha() {
    setCodeLoading(true);
    http.get('/gateway/verification/code').then((res: any) => {
      console.log(res)
      if (res.code === 0) {
        setCounter(30)
        notification.open({message: '验证码', description: res.data.code, duration: 25});
      } else {
        setCounter(0)
        setCodeLoading(false)
      }
    }).finally(() => setCodeLoading(false))
  }

  return (
    <div className={styles.container}>
      <div className={styles.titleContainer}>
        <div><img className={styles.logo} src={logo} alt="logo"/></div>
        <div className={styles.desc}>灵活、强大、易用的开源运维平台</div>
      </div>

      <div className={styles.formContainer}>
        <Tabs className={styles.tabs} defaultActiveKey='default' onChange={activeKey => setLoginType(activeKey)}>
          <Tabs.TabPane tab="普通登录" key="default"/>
          <Tabs.TabPane tab="LDAP登录" key="ldap"/>
        </Tabs>

        <Form form={form}>
          <Form.Item name="username" className={styles.formItem}>
            <Input
              size="large"
              autoComplete="off"
              placeholder="请输入账户"
              prefix={<UserOutlined className={styles.icon}/>}/>
          </Form.Item>
          <Form.Item name="password" className={styles.formItem}>
            <Input
              size="large"
              type="password"
              autoComplete="off"
              placeholder="请输入密码"
              onPressEnter={handleSubmit}
              prefix={<LockOutlined className={styles.icon}/>}/>
          </Form.Item>

          <Form.Item hidden={loginType !== 'default'} name="captcha" className={styles.formItem}>
            <div style={{display: 'flex'}}>
              <Form.Item noStyle name="captcha">
                <Input
                  size="large"
                  autoComplete="off"
                  placeholder="请输入验证码"
                  prefix={<MailOutlined className={styles.icon}/>}/>
              </Form.Item>
              {counter > 0 ? (
                <Button disabled size="large" style={{marginLeft: 8}}>{counter} 秒后重新获取</Button>
              ) : (
                <Button size="large" loading={codeLoading} style={{marginLeft: 8}} onClick={handleCaptcha}>
                  获取验证码
                </Button>
              )}
            </div>
          </Form.Item>
        </Form>

        <Button
          block
          size="large"
          type="primary"
          className={styles.button}
          loading={loading}
          onClick={handleSubmit}>
          登录
        </Button>
      </div>

      <div className={styles.footerZone}>
        <div className={styles.linksZone}>
          <a className={styles.links} title="官网" href="https://gitee.com/756585379" target="_blank"
             rel="noopener noreferrer">官网</a>
          <a className={styles.links} title="Gitee" href="https://gitee.com/756585379" target="_blank"
             rel="noopener noreferrer"><GithubOutlined/></a>
          <a title="文档" href="https://gitee.com/756585379" target="_blank"
             rel="noopener noreferrer">文档</a>
        </div>
        <div style={{color: 'rgba(0, 0, 0, .45)'}}>Copyright <CopyrightOutlined/>
          {new Date().getFullYear()} By qq756585379
        </div>
      </div>
    </div>
  )
}

export default Login
